package com.gitee.magic.jdbc.persistence.source.jdbc.sqlplus.conditions.update;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import com.gitee.magic.jdbc.persistence.source.jdbc.sqlplus.conditions.AbstractWrapper;
import com.gitee.magic.jdbc.persistence.source.jdbc.sqlplus.conditions.segments.MergeSegments;
import com.gitee.magic.jdbc.persistence.source.jdbc.sqlplus.toolkit.EmptyUtils;
import com.gitee.magic.jdbc.persistence.source.jdbc.sqlplus.toolkit.StringPool;

/**
 * <p>
 * Update 条件封装
 * </p>
 *
 * @author Start
 */
public class UpdateWrapper extends AbstractWrapper<String, UpdateWrapper> {

    /**
     * SQL 更新字段内容，例如：name='1',age=2
     */
    private final List<String> sqlSet;

    public UpdateWrapper() {
        // 如果无参构造函数，请注意实体 NULL 情况 SET 必须有否则 SQL 异常
        this.sqlSet = new ArrayList<>();
        this.initNeed();
    }

    private UpdateWrapper(List<String> sqlSet, AtomicInteger paramNameSeq,
                          Map<String, Object> paramNameValuePairs, MergeSegments mergeSegments) {
        this.sqlSet = sqlSet;
        this.paramNameSeq = paramNameSeq;
        this.paramNameValuePairs = paramNameValuePairs;
        this.expression = mergeSegments;
    }

    @Override
    public String getSqlSet() {
        if (EmptyUtils.isEmpty(sqlSet)) {
            return null;
        }
        return String.join(StringPool.COMMA, sqlSet);
    }

    /**
     * <p>
     * SQL SET 字段
     * </p>
     *
     * @param column 字段
     * @param val    值
     */
    public UpdateWrapper set(String column, Object val) {
        return this.set(true, column, val);
    }

    /**
     * <p>
     * SQL SET 字段
     * </p>
     *
     * @param condition 操作条件
     * @param column    字段
     * @param val       值
     */
    public UpdateWrapper set(boolean condition, String column, Object val) {
        if (condition) {
            sqlSet.add(String.format("%s=%s", column, formatSql("{0}", val)));
        }
        return typedThis;
    }

    /**
     * <p>
     * SET 部分 SQL
     * </p>
     *
     * @param sql SET 部分内容
     */
    public UpdateWrapper setSql(String sql) {
        sqlSet.add(sql);
        return typedThis;
    }

    @Override
    protected String columnToString(String column) {
        return column;
    }

    @Override
    protected UpdateWrapper instance(AtomicInteger paramNameSeq, Map<String, Object> paramNameValuePairs) {
        return new UpdateWrapper(sqlSet, paramNameSeq, paramNameValuePairs, new MergeSegments());
    }
}
